package com.xunmall.email.service;

import com.xunmall.base.entity.MessageVo;
import com.xunmall.base.exception.BadRequestException;
import com.xunmall.base.exception.BaseException;
import com.xunmall.base.util.RegExpValidatorUtils;
import com.xunmall.email.dto.Email;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Created by Gimgoog on 2018/2/6.
 */
public class EmailValidate {
    private static Validator validator;

    public static void Validate(Email email) {
        MessageVo messages = new MessageVo();

        if (validator == null) {
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            validator = factory.getValidator();
        }

        Set<ConstraintViolation<Email>> constraintViolations = validator.validate(email);
        if(constraintViolations.size() > 0){
            constraintViolations.stream().forEach(
                    item -> messages.addMessageObj(BaseException.ERR_9999, item.getMessage(), item.getPropertyPath().toString())
            );
        }
        if (StringUtils.isNotEmpty(email.getAffixName()) && ArrayUtils.isEmpty(email.getAffixContent())) {
            messages.addMessageObj(BaseException.ERR_9999, "附件不存在", "");
        }
        if (StringUtils.isNotEmpty(email.getAffixName()) && ArrayUtils.isNotEmpty(email.getAffixContent())) {
            if(email.getAffixContent().length > 1000000) {
                messages.addMessageObj(BaseException.ERR_9999, "文件大小超出限制", "");
            }
        }
        if (StringUtils.isNotEmpty(email.getAddressees()) && !RegExpValidatorUtils.isEmail(email.getAddressees())) {
            messages.addMessageObj(BaseException.ERR_9999, "邮件地址格式错误", "");
        }

        if(messages.getReasons().size() > 0) {
            throw new BadRequestException(messages, "");
        }
    }
}
